<template>
    <div class="container">
        <el-card class="card">
            <!-- <div class="header">
                <el-button v-for="(item, index) in dateOptions" :key="index" @click="selectDate(item.value)">
                    {{ item.label }}
                </el-button>
            </div> -->
            <el-form :model="formData" ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="货品编号" prop="productCode">
                    <el-input v-model="formData.productCode" placeholder="请输入货品编号名称" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="search">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
            <!-- <el-form ref="elForm" :model="formData" :rules="rules" size="mini" label-width="100px"
                label-position="left">

                <el-col :span="7">
                    <el-form-item label="货品编号" prop="productName">
                        <el-input v-model="formData.productName" placeholder="请输入货品编号" clearable
                            :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form> -->
            <div class="statistics">
                <el-card class="stat-card" v-for="(stat, index) in statistics" :key="index">
                    <div class="stat-item">
                        <div class="stat-value" :style="{ color: stat.color1 }">
                            <count-to :start-val="0" :end-val="stat.value1" :duration="2600" />
                            <div class="sub-title">{{ stat.title1 }}</div>
                        </div>
                        <div class="stat-value" :style="{ color: stat.color2 }">
                            <count-to :start-val="0" :end-val="stat.value2" :duration="2600" />
                            <div class="sub-title">{{ stat.title2 }}</div>
                        </div>
                    </div>
                </el-card>
            </div>

            <el-table :data="tableData" style="width: 100%">
                <el-table-column fixed prop="index" label="序号" width="60"></el-table-column>

                <el-table-column prop="productCode" label="货品编号" width="160"></el-table-column>
                <el-table-column prop="productName" label="货品名称" width="100"></el-table-column>
                <el-table-column label="状态" align="center" prop="productStatus">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.py_product_type" :value="scope.row.productStatus" />
                    </template>
                </el-table-column>
                <el-table-column prop="productModel" label="规格型号" width="100"></el-table-column>
                <el-table-column prop="productUnit" label="单位" width="80">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.py_product_unit" :value="scope.row.productUnit" />
                    </template>
                </el-table-column>
                <el-table-column prop="warehouseName" label="仓库名称" width="120"></el-table-column>
                <el-table-column prop="locationName" label="库位名称" width="120"></el-table-column>
                <el-table-column prop="currentInventory" label="当前库存" width="100"></el-table-column>
                <el-table-column prop="inventoryValue" label="库存金额" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.inventoryValue.toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column prop="pendingIn" label="待入库" width="100"></el-table-column>
                <el-table-column prop="pendingOut" label="待出库" width="100"></el-table-column>
                <el-table-column prop="availableInventoryValue" label="可用库存金额" width="150">
                    <template slot-scope="scope">
                        {{ scope.row.availableInventoryValue.toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column prop="inventoryUpperLimit" label="库存上限" width="100"></el-table-column>
                <el-table-column prop="inventoryLowerLimit" label="库存下限" width="100">
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="formData.pageNum" :limit.sync="formData.pageSize"
                @pagination="getList" />
        </el-card>
    </div>
</template>

<script>
import {
    selectAllBsWarehouse, whInventoryTotle, selectAllSysUserByParentId, selectAllSysDeptByID, selectAllSysDept, WhInventoryList
} from "@/api/inbound/inbound";
import CountTo from 'vue-count-to'
export default {
    components: { CountTo },
    dicts: ['py_instock_type', 'py_product_unit', 'py_product_type'],
    data() {
        return {
            total: 0,
            jbr: [],
            // selectedDate: 'today',  // 默认选择
            cascaderOptions: [],
            cascaderProps: {
                value: 'value',
                label: 'label',
                children: 'children',
                // checkStrictly: true
            },
            // dateOptions: [
            //     { label: '今日', value: 'today' },
            //     { label: '昨日', value: 'yesterday' },
            //     { label: '本周', value: 'thisWeek' },
            //     { label: '上月', value: 'lastMonth' },
            //     { label: '全部', value: '' },
            //     // { label: '自定义时间', value: 'custom' },
            // ],
            formData: {
                pageNum: 1,
                pageSize: 10,
                productCode: '',

            },
            warehouseIds: [],//仓库名称id数组
            rules: {},
            statistics: [
                {
                    title1: '当前库存数量',
                    value1: 50,
                    title2: '当前库存金额',
                    value2: 500.00,
                    color1: '#409EFF',
                    color2: '#F56C6C',
                },
                // {
                //     title1: '入库数量',
                //     value1: 100,
                //     title2: '出库数量',
                //     value2: 100,
                //     color1: '#67C23A',
                //     color2: '#E6A23C',
                // },
                {
                    title1: '待入库',
                    value1: 100,
                    title2: '待出库',
                    value2: 100,
                    color1: '#67C23A',
                    color2: '#E6A23C',
                },
            ],
            tableData: [
            ],
        };
    },
    created() {
        this.fetchItems();
        this.getList();
        // // 确保selectAllBsWarehouse是一个函数并调用它
        // selectAllBsWarehouse().then(response => {
        //     this.warehouseIds = response.data.map(item => ({
        //         value: item.warehouseId,
        //         label: item.warehouseName
        //     }));
        // }).catch(error => {
        //     console.error('Fetching warehouses failed:', error);
        // });
        whInventoryTotle().then(response => {
            console.log('统计:', JSON.stringify(response, null, 2));
            this.statistics[0].value1 = response.currentInventory
            this.statistics[0].value2 = response.inventoryValue
            this.statistics[1].value1 = response.pendingIn
            this.statistics[1].value2 = response.pendingOut
            // this.statistics[2].value = response.inventoryAmount
        }).catch(error => {
            console.error('Fetching warehouses failed:', error);
        });

    },
    methods: {

        handleInventoryTypeChange(newVal) {

        },

        selectDate(value) {
            console.log('选择响应:', value);
            this.formData.inboundDate = value;
            this.getList();
            // 这里可以根据选择的日期更新表格数据
        },
        search() {

            this.formData.pageNum = 1;
            // 执行查询操作
            console.log('查询数据', this.formData);
            this.getList();
        },
        reset() {

            this.formData = {

                productName: '',

            };
        },
        getList() {
            // this.loading = true;
            WhInventoryList(this.formData).then(response => {
                console.log('后端响应阿萨:', JSON.stringify(response, null, 2));
                // this.tableData = response.rows;
                this.tableData = response.rows.map((item, index) => ({
                    ...item,
                    index: index + 1
                }));
                this.total = response.total;
                // this.loading = false;
            });
        },
        parseTime(time, format) {
            if (!time) return '';
            const date = new Date(time);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return format.replace(/yyyy/g, year)
                .replace(/MM/g, month)
                .replace(/dd/g, day)
                .replace(/HH/g, hours)
                .replace(/mm/g, minutes)
                .replace(/ss/g, seconds);
        },
        async fetchItems() {
            try {
                const response = await selectAllSysDept();
                if (Array.isArray(response)) {
                    this.cascaderOptions = await this.convertToCascaderOptions(response);
                } else {
                    console.error('Expected an array, but got:', response);
                }
            } catch (error) {
                console.error('Error fetching items:', error);
            }
        },

        async convertToCascaderOptions(data) {
            if (!Array.isArray(data)) {
                console.error('Expected an array, but got:', data);
                return [];
            }

            // 创建一个映射，用于快速查找父项
            const itemMap = new Map(data.map(item => [item.deptId, item]));
            const topLevelItems = [];

            for (const item of data) {
                if (item.parentId === 0) {
                    topLevelItems.push(await this.createOption(item));
                } else {
                    const parentItem = itemMap.get(item.parentId);
                    if (parentItem) {
                        const childItem = await this.createOption(item);
                        if (!parentItem.children) {
                            parentItem.children = [];
                        }
                        parentItem.children.push(childItem);
                    }
                }
            }

            return topLevelItems;
        },

        async createOption(item) {
            const [children, users] = await Promise.all([
                this.fetchChildren(item.deptId),
                this.fetchUsers(item.deptId)
            ]);
            return {
                value: item.deptId,
                label: item.deptName,
                children: children,
                users: users
            };
        },

        async fetchUsers(deptId) {
            try {
                const response = await selectAllSysUserByParentId(deptId);
                if (Array.isArray(response)) {
                    return response.map(user => ({
                        value: user.userId,
                        label: user.userName
                    }));
                } else {
                    console.error('Expected an array, but got:', response);
                    return [];
                }
            } catch (error) {
                console.error('Error fetching users:', error);
                return [];
            }
        },

        async fetchChildren(parentId) {
            try {
                const response = await selectAllSysDeptByID(parentId);
                if (Array.isArray(response)) {
                    return Promise.all(response.map(async (item) => {
                        const [users, children] = await Promise.all([
                            this.fetchUsers(item.deptId),
                            this.fetchChildren(item.deptId) // 递归获取子部门
                        ]);
                        return {
                            value: item.deptId,
                            label: item.deptName,
                            children: [
                                ...children,
                                ...users.map(user => ({
                                    value: user.value,
                                    label: user.label,
                                    // isUser: true
                                }))
                            ]
                        };
                    }));
                } else {
                    console.error('Expected an array, but got:', response);
                    return [];
                }
            } catch (error) {
                console.error('Error fetching children:', error);
                return [];
            }
        },
        handleChange(value) {
            // const currentSelectedValue = value[value.length - 1];
            this.jbr = value;
            console.log('后端响应:', value);
        },
    },
};
</script>

<style scoped>
.container {
    padding: 20px;
}

.card {
    padding: 20px;
}

.header {
    margin-bottom: 20px;
}

.form-row {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 10px;
}

.form-row .el-form-item {
    margin-right: 20px;
    /* 调整每个表单项之间的间距 */
}

.statistics {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;
    gap: 20px;
    /* 卡片之间的间距 */
}

.stat-card {
    flex: 1 1 30%;
    /* 适应不同屏幕大小 */
    padding: 20px;
    text-align: center;
}

.stat-item {
    display: flex;
    justify-content: space-around;
    /* 均匀分布 */
}

.stat-value {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    /* 中心对齐 */
    /* font-size: 20px; */
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
}
</style>
